<template>
  <div>
    <div class="name">销售额 (元)</div>
    <div ref="chartContainer" class="g2-bar-chart"></div>
  </div>
</template>

<script>
import { Chart } from "@antv/g2";

export default {
  props: {
    chartData: {
      type: Array,
      required: true,
    },
    chartConfig: {
      type: Object,
      default: () => ({
        xField: "day",
        yField: "money",
        color: "#1890ff",
        animation: true,
        padding: [20, 40, 60, 60],
        height: 330,
      }),
    },
  },
  data() {
    return {
      chart: null,
      resizeTimer: null,
    };
  },
  watch: {
    chartData: {
      handler(newVal) {
        this.updateChartData(newVal);
      },
      deep: true,
    },
    chartConfig: {
      handler() {
        this.rebuildChart();
      },
      deep: true,
    },
  },
  mounted() {
    this.initChart();
    this.addResizeListener();
  },
  methods: {
    // 原生实现防抖函数
    debounce(func, wait) {
      return () => {
        clearTimeout(this.resizeTimer);
        this.resizeTimer = setTimeout(func, wait);
      };
    },

    initChart() {
      this.chart = new Chart({
        container: this.$refs.chartContainer,
        autoFit: true,
        height: this.chartConfig.height,
        padding: this.chartConfig.padding,
        axis: {
          x: {
            title: false,
            labelTransform: "rotate(45)",
          },
          y: {
            title: false,
          },
        },
      });

      this.configureChart();
      this.chart.render();
    },
    updateChartData(newData) {
      if (this.chart) {
        this.chart.changeData(newData);
      }
    },
    configureChart() {
      this.chart
        .interval()
        .data(this.chartData)
        .encode("x", "day")
        .encode("y", "money");
    },
    addResizeListener() {
      const handler = this.debounce(() => {
        if (this.chart) {
          this.chart.forceFit();
        }
      }, 200);
      window.addEventListener("resize", handler);
      this.$once("hook:beforeDestroy", () => {
        window.removeEventListener("resize", handler);
      });
    },
  },
};
</script>

<style scoped>
.g2-bar-chart {
  width: 100%;
  margin: 0 auto;
  min-height: 300px;
}
.name {
  margin: 35px;
}
</style>
